package pub.tbc.toolkit.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author tbc
 * @version 1.0 {2016年7月7日 下午3:03:43}
 */
public class Files {
	private static Logger log = LoggerFactory.getLogger(Files.class);

	public static File getFile(String file) {
		return new File(file);
	}

	public static FileInputStream getFileInputStream(File file) {
		try {
			return new FileInputStream(file);
		} catch (FileNotFoundException e) {
			log.error("file not found", e);
			throw new RuntimeException(e);
		}
	}

	public static InputStream getInputStream(File file) {
		return getFileInputStream(file);
	}

	public static InputStreamReader getInputStreamReader(File file) {
		return getInputStreamReader(file, "utf-8");
	}

	public static InputStreamReader getInputStreamReader(File file, String charset) {
		return getInputStreamReader(getInputStream(file), charset);
	}

	public static InputStreamReader getInputStreamReader(InputStream in) {
		return new InputStreamReader(in);
	}

	public static InputStreamReader getInputStreamReader(InputStream in, String charset) {
		try {
			return new InputStreamReader(in, charset);
		} catch (UnsupportedEncodingException e) {
			log.error("file not found", e);
			throw new RuntimeException(e);
		}
	}

	public static String readByte(File file) {
		try {
			InputStream in = new FileInputStream(file);
			return read(in);
		} catch (FileNotFoundException e) {
			log.error("create FileInputStream failure", e);
			throw new RuntimeException(e);
		}
	}

	public static String readString(File in) {
		return readString(in, "utf-8");
	}

	public static String readString(File in, String charset) {
		String str = null;
		BufferedReader br;
		StringBuilder sb = new StringBuilder();
		try {
			br = new BufferedReader(getInputStreamReader(in, charset));
			while ((str = br.readLine()) != null) {
				sb.append(str);
			}
		} catch (IOException e) {
			log.error("IO 异常， readLine 出错", e);
			throw new RuntimeException(e);
		}
		return sb.toString();
	}

	public static String read(InputStream in) {
		byte[] bytes = new byte[1024];
		StringBuilder sb = new StringBuilder();
		try {
			while ((in.read(bytes)) != -1) {
				sb.append(new String(bytes));
			}
		} catch (IOException e) {
			log.error("read inputStream failure; IO exception", e);
			throw new RuntimeException(e);
		}
		return sb.toString();
	}

	public static String read(InputStream in, String charset) {

		return null;
	}

}
